package com.redis.demo.core.dao.impl;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import com.redis.demo.core.dao.IMemberDao;
import com.redis.demo.core.entity.Member;

/**
 * 会员管理 dao: 用jedis实现的dao
 * 
 * @author sean
 * 
 */

@Repository
public class MemberDaoByJedis extends BaseDaoByRedis<Member> implements
		IMemberDao {

	public MemberDaoByJedis() {
		super(Member.class);
	}

	@Override
	public Member saveMember(Member member) {
		String id = member.getId();
		if (StringUtils.isEmpty(id)) {
			id = uuid();
		}

		member.setId(id);
		byte[] key = key(id);
		if (jedis.exists(key)) {
			logger.debug("member {} is exists!", id);
		}
		byte[] bytes = serial(member);
		jedis.set(key, bytes);
		jedis.save();
		return member;
	}

	@Override
	public Member getMemberById(String id) {
		byte[] key = key(id);
		byte[] bytes = jedis.get(key);
		return unSerial(bytes);
	}

	@Override
	public List<Member> getAllMembers() {
		try {
			String pattern = simpleName() + "*";
			Set<byte[]> keys = jedis.keys(pattern.getBytes("UTF-8"));
			List<Member> members = new ArrayList<Member>();
			if (!keys.isEmpty()) {
				for (byte[] key : keys) {
					byte[] value = jedis.get(key);
					Member member = unSerial(value);
					assert member != null;
					members.add(member);
				}
			}

			return members;
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public boolean deleteMemberById(String id) {

		byte[] key = key(id);
		return jedis.del(key) == 1;
	}
}
